﻿using com.yoozoo.gta.Extension;
using LogSystem;
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Serialization;
using Yoozoo.Framework.Manager.ResourceSystem.Runtime;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Yoozoo.Modules.Update;

namespace Yoozoo.UI.YGUI
{
    /// <summary>
    /// 对YImage类 
    /// </summary>
    public class YImageWrap : IWebImageHandler
    {
        static void ActionGet(YImageWrap wrap)
        {
            s_using.Add(wrap);
        }

        static void ActionRelease(YImageWrap wrap)
        {
            wrap.OnDestroy();
            s_using.Remove(wrap);
        }

        static ObjectPool<YImageWrap> s_pool = new ObjectPool<YImageWrap>(ActionGet, ActionRelease);
        static List<YImageWrap> s_using = new List<YImageWrap>(100);

        public static YImageWrap Get(YImage yImage)
        {
            var wrap = s_pool.Get();
            wrap.m_target = yImage;
            return wrap;
        }

        public static void Collect()
        {
            for (int i = s_using.Count; i >= 0; --i)
            {
                if (s_using[i].m_target.Invalid())
                {
                    s_pool.Release(s_using[i]);
                }
            }
        }

        private string m_spriteName;
        private string m_materialName;
        private YImage m_target;

        private WebImageHandler _webImageHandler;
        
        private ResLoader _resLoaderMaterial;
        private ResLoader _resLoaderTexture;

        private Action<string> _successDelegate;

        private Action<string> _failDelegate;
        [NonSerialized]
        private bool IsRepidMode = false;  //谨慎使用，会卡顿
        [NonSerialized]
        private int  priority = 0;

        public string spriteName
        {
            get { return m_spriteName; }
            set
            {
                if (m_spriteName == value)
                {
                    _successDelegate?.Invoke(value);
                    return; 
                }
                
                // eg: UI/GUIBig/ActivityDaily/
                if (value != null && value.EndsWith("/"))
                {
                    Debug.LogWarningFormat(LogModule.UIFramework, "spriteName is empty: {0}", value);
                    return;
                }

                if (WebImageManager.IsFromWeb(this.m_spriteName))
                    WebImageManager.Instance.RemoveLoadWebImageHandler(this, this.m_spriteName, _webImageHandler);

                m_spriteName = value;

                //检查需要操作的对象是否存在
                //CheckTarget();
                if(GameHelper.AotCodeVersion >= 20240723)
                {
                    if (string.IsNullOrEmpty(value))
                    {
                        m_target.sprite = null;
                        _resLoaderTexture?.Recycle2Cache();
                        _resLoaderTexture = null;
                        return;
                    }
                }
                

                if (m_target.Invalid())
                {
                    //Debug.LogWarning($"@-----instId:{gameObject.GetInstanceID()} {transform.name} Invalid:{m_target.Invalid()} {value}");
                    return;
                }

                if (WebImageManager.IsFromWeb(value))
                {
                    if (_webImageHandler == null) _webImageHandler = new WebImageHandler(this);
                    WebImageManager.Instance.AddLoadWebImageHandler(this, value, _webImageHandler);
                }
                else
                {
                    _resLoaderTexture = ResLoader.Alloc();
                    _resLoaderTexture.forceRelease = m_target.forceRelease || YImageBinder.NeedForceRelease(value);
                    
                    var path = value;
                    if (!path.StartsWith("Assets/ResourcesAssets/"))
                    {
                        path = "Assets/ResourcesAssets/" + value;
                    }

                    if (!path.EndsWith(".png"))
                    {
                        path += ".png";
                    }

                    

                    Res.ResLoadCompleteCallBack resLoadCompleteCallBack = (success, name, asset) =>
                    {
                        if(m_target.Invalid())
                        {
                            return;
                        }
                        if (!success)
                        {
                            m_target.sprite = null;
                            UnityEngine.Debug.LogError("dont has this sprite:" + value, m_target);
                            m_spriteName = null;
                        }
                        else
                        {
                            if (asset == null)
                            {
                                Debug.LogWarning(value);
                                return;
                            }

                            if (m_spriteName == value)
                            {
                                m_target.sprite = asset as Sprite;
                                _successDelegate?.Invoke(value);
                            }
                        }
                    };
                    if (IsRepidMode)
                    {
                        _resLoaderTexture.Add2LoadRapid(path, typeof(Sprite), resLoadCompleteCallBack).Load();
                    }
                    else
                    {
                        
                        if (GameHelper.AotCodeVersion >= 20240717)
                        {
                            functionWrap(_resLoaderTexture, path, typeof(Sprite), priority, resLoadCompleteCallBack);
                        }
                        else
                        {
                            _resLoaderTexture.Add2Load(path, typeof(Sprite), resLoadCompleteCallBack).Load();    
                        }
                        
                    }
                    
                }
                
            }
        }

        private void functionWrap(ResLoader _resLoaderTexture,string path, Type type, int priority,Res.ResLoadCompleteCallBack listener = null)
        {
            _resLoaderTexture.Add2LoadWithPriority(path, typeof(Sprite), priority,listener).Load();    
        }
        public void OnSetupSuccessDelegate(Action<string> successDelegate)
        {
            _successDelegate = successDelegate;
        }
        
        public void LoadWebImageSuccess(Texture2D texture, string imageUrl)
        {
            if (!m_target)
                return;
            
            if (this.spriteName == imageUrl && texture != null)
            {
                this.m_target.sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),
                    new Vector2(0.5f, 0.5f));
                _successDelegate?.Invoke(imageUrl);
            }
        }

        public void OnSetupFailDelegate(Action<string> failDelegate)
        {
            _failDelegate = failDelegate;
        }

        public void LoadWebImageFail(string imageUrl)
        {
            _failDelegate?.Invoke(imageUrl);
        }

        public void LoadSync()
        {
            //this.priority = Int32.MaxValue;
            this.IsRepidMode = true;
        }

        public void Release()
        {
            if (WebImageManager.IsFromWeb(m_spriteName))
            {
                WebImageManager.Instance.RemoveLoadWebImageHandler(this,m_spriteName,_webImageHandler);
                _webImageHandler = null;
            }

            _successDelegate = null;
            _failDelegate = null;
            s_pool.Release(this);
        }

        void OnDestroy()
        {
            //UnityEngine.Debug.LogWarning($"OnDestroy--inst:{transform.GetInstanceID()}--------spriteName:{m_spriteName} target={transform.Valid()}  image:{m_target.Valid()}");
            m_target = null;
            m_spriteName = string.Empty;
            m_materialName = string.Empty;

            _resLoaderTexture?.Recycle2Cache();
            _resLoaderTexture = null;

            _resLoaderMaterial?.Recycle2Cache();
            _resLoaderMaterial = null;
            
            if (WebImageManager.IsFromWeb(m_spriteName))
            {
                WebImageManager.Instance.RemoveLoadWebImageHandler(this,m_spriteName,_webImageHandler);
                _webImageHandler = null;
            }
            
            _successDelegate = null;
            _failDelegate = null;
        }
    }
}
